<template>
  <el-card class="form-container" shadow="never">
    <el-form
      :model="course"
      :rules="rules"
      ref="courseFrom"
      label-width="150px"
      size="small">
      <el-form-item label="课程名称：" prop="courseName">
        <el-input v-model="course.courseName" class="input-width"></el-input>
      </el-form-item>
      <el-form-item label="课程封面：" prop="coursePic">
        <single-upload v-model="course.coursePic"></single-upload>
      </el-form-item>
      <el-form-item label="来源机构：" prop="deptId">
        <el-select
          v-model="course.deptId"
          filterable
          remote
          reserve-keyword
          placeholder="请输入关键词"
          :remote-method="remoteMethod"
          :loading="loading"
          @change="deptChange">
          <el-option
            v-for="item in deptOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="类型：" prop="courseType">
        <el-cascader
          :disabled="!course.deptId"
          v-model="course.courseType"
          :options="courseTypeOptions"
          :props="{
            children:'subset',
            label: 'typeName',
            value: 'id'
          }"
          @change="courseChange">
        </el-cascader>
      </el-form-item>
      <el-form-item label="更新频率：" prop="frequency">
        <el-input v-model="course.frequency" class="input-width"></el-input>
      </el-form-item>
      <el-form-item label="售课方式：" prop="priceType">
        <el-select v-model="course.priceType" placeholder="请选择" @focus="getPriceType">
          <el-option
            v-for="item in priceTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="价格：" prop="price">
        <el-input v-model="course.price" class="input-width"></el-input>
      </el-form-item>
      <el-form-item label="讲师：">
        <el-input v-model="course.teacher" class="input-width"></el-input>
      </el-form-item>
      <el-form-item label="课程简介：">
        <el-input
          class="input-width"
          type="textarea"
          :rows="5"
          placeholder="请输入内容"
          v-model="course.courseDesc">
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('courseFrom')">提交</el-button>
        <!--<el-button v-if="!isEdit" @click="resetForm('courseFrom')">重置</el-button>-->
        <el-button @click="back">返回</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import SingleUpload from '@/components/Upload/singleUpload'
import { curCourseBaseSave, curCourseBaseGetById, curCourseBaseUpdate, commonList, umsDeptList, curCourseTypeListByDeptId } from '@/api/course'

const listToTree = (list, tree, parentId) => {
  list.forEach(item => {
    // 判断是否为父级菜单
    if (item.parentId === parentId) {
      const child = {
        ...item,
        typeName: item.name,
        subset: []
      }
      // 迭代 list， 找到当前菜单相符合的所有子菜单
      listToTree(list, child.subset, item.id)
      // 删掉不存在 children 值的属性
      if (child.subset.length <= 0) {
        delete child.subset
      }
      // 加入到树中
      tree.push(child)
    }
  })
}

const defaultCourse = {
  courseName: null,
  coursePic: null,
  deptId: null,
  courseType: null,
  frequency: null,
  priceType: null,
  price: null,
  teacher: null,
  courseDesc: null
}
export default {
  name: 'CourseDetail',
  components: { SingleUpload },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      course: {},
      deptOptions: [],
      courseTypeOptions: [],
      priceTypeOptions: [],
      loading: false,
      rules: {
        courseName: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        coursePic: [
          { required: true, message: '请选择课程封面', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '请选择', trigger: 'blur' }
        ],
        courseType: [
          { required: true, message: '请选择', trigger: 'blur' }
        ],
        frequency: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        priceType: [
          { required: true, message: '请选择售课方式', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    setTimeout(() => {
      this.$refs['courseFrom'].resetFields()
    }, 0)
    if (this.isEdit) {
      // 获取课程详情
      curCourseBaseGetById({ id: this.$route.query.id }).then(response => {
        this.deptOptions = [{ value: response.data.deptId, label: response.data.deptName }]
        this.priceTypeOptions = [{ value: response.data.priceType, label: response.data.priceTypeName }]

        const tree = []
        listToTree(response.data.typeList, tree, '0')
        this.courseTypeOptions = tree
        this.course = response.data
        this.course.courseType = response.data.typeList.map((item) => {
          return parseInt(item.id)
        })
        this.getCourseType(this.course.deptId)
      })
    } else {
      this.getCourseType()
      this.course = Object.assign({}, defaultCourse)
    }
  },
  methods: {
    onSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('是否提交数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const params = {
              id: this.$route.query.id,
              ...this.course,
              courseType: this.course.courseType[this.course.courseType.length - 1],
            }

            if (this.isEdit) {
              curCourseBaseUpdate(params).then(response => {
                // this.$refs[formName].resetFields()
                this.$message({
                  message: '修改成功',
                  type: 'success',
                  duration: 1000
                })
                this.$router.back()
              })
            } else {
              curCourseBaseSave(params).then(response => {
                // this.$refs[formName].resetFields()
                // this.course = Object.assign({}, defaultCourse)
                this.$message({
                  message: '提交成功',
                  type: 'success',
                  duration: 1000
                })
                this.$router.back()
              })
            }
          })
        } else {
          this.$message({
            message: '验证失败',
            type: 'error',
            duration: 1000
          })
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.course = Object.assign({}, defaultCourse)
    },
    getPriceType (e) {
      if (e) {
        this.priceTypeOptions = []
        // 获取售课方式枚举
        commonList({ commonType: 'sell_mode' }).then(response => {
          const list = response.data
          list.map((item) => {
            const { id, commonCode, commonDesc } = item
            const listB = {
              id: id,
              value: commonCode,
              label: commonDesc
            }
            this.priceTypeOptions.push(listB)
          })
        })
      }
    },
    getCourseType (deptId) {
      const params = {}
      // 获取课程类型枚举
      if (deptId) {
        params.deptId = deptId
      }
      curCourseTypeListByDeptId(params).then(response => {
        this.courseTypeOptions = response.data.list
      })
    },
    remoteMethod (query) {
      // 来源机构
      if (query !== '') {
        this.loading = true
        umsDeptList({ pageSize: 50, pageNum: 1, deptName: query }).then(response => {
          this.loading = false
          this.deptOptions = response.data.list.map(item => {
            return { value: item.id, label: item.deptName }
          })
        })
      } else {
        this.deptOptions = []
      }
    },
    deptChange (deptId) {
      this.getCourseType(deptId)
    },
    courseChange (e) {
      console.log(e)
    },
    back () {
      this.$router.go(-1)
    }
  }

}
</script>
<style scoped>
  .input-width {
    width: 70%;
  }
</style>
